package net.pzc.filechooser;

import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.SwingUtilities;

import sun.awt.shell.ShellFolder;

public class ListUserHomeAction extends Thread {

	private ToggleButtonGroupPanel ui = null;
	private DefaultComboBoxModel model = null;

	public ListUserHomeAction(ToggleButtonGroupPanel ui) {
		this.ui = ui;
		this.model = (DefaultComboBoxModel) ui.getModel();
		ui.setEnabled(false);
		ui.getParent().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
	}

	@Override
	public void run() {

		ButtonGroup group = new ButtonGroup();

		String desktopPath = PathGetter.getDesktop();
		makeButton(desktopPath, group);

		String documentsPath = PathGetter.getDocuments();
		makeButton(documentsPath, group);

		// String userHomePath = System.getProperty("user.home");
		// makeButton(userHomePath, group);

		try {
			finishWork();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void makeButton(String path, ButtonGroup group) {
		final File file = new File(path);
		ShellFolder shellFolder;
		try {
			shellFolder = ShellFolder.getShellFolder(file);

			Image bigIcon = shellFolder.getIcon(true);
			BufferedImage bi = new BufferedImage(bigIcon.getWidth(null), bigIcon.getHeight(null), BufferedImage.TYPE_INT_ARGB);
			Graphics g = bi.getGraphics();
			g.drawImage(bigIcon, 0, 0, null);
			g.dispose();
			String despName = shellFolder.getDisplayName();

			FileItem fi = new FileItem();
			fi.setIcon(bi);
			fi.setSysDisplayName(despName);
			fi.setAbsolutePath(file.getAbsolutePath());
			fi.setName(file.getName());

			updateUI(fi);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	private void updateUI(final FileItem fi) throws Exception {
		SwingUtilities.invokeAndWait(new Runnable() {

			public void run() {
				model.addElement(fi);
			}

		});
	}

	private void finishWork() throws Exception {
		SwingUtilities.invokeAndWait(new Runnable() {

			public void run() {
				ui.getParent().setCursor(Cursor.getDefaultCursor());
				ui.setEnabled(true);
			}

		});
	}
}
